package com.jp.knowledge.my.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.adapter.RightContentAdapter;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.CommTags;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.adapter.LeftAdapter;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.FlowLayout;

import org.xutils.view.annotation.ViewInject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 选取更多角色
 */
public class MoreRoleActivity extends SlidingActivity implements ResultSubscriber.OnResultListener, View.OnClickListener {


    private final int GET_COMM_TAG_LIST_CODE = 0x000001;//获取标标签列表
    private final int GET_COMM_INDUSTRY_LIST_CODE = 0x000002;//获取行业标签
    public static final int ROLE_RESULT_CODE = 0x00012;//获取标标签列表
    public static final int INDUSTRY_RESULT_CODE = 0x0013;//获取标标签列表

    private boolean isSkill;//是否是角色


    @ViewInject(R.id.flow_layout)
    private FlowLayout  flowLayout;

    @ViewInject(R.id.left_menu)
    private RecyclerView leftMune;

    @ViewInject(R.id.right_content)
    private RecyclerView rightContent;

    @ViewInject(R.id.select_content)
    private RecyclerView selectContent;

    @ViewInject(R.id.select_btn)
    private TextView selectBtn;

    @ViewInject(R.id.select_num)
    private TextView selectNum;

    private RightContentAdapter rightAdapter;

    private LeftAdapter leftAdapter;

    private List<CommTags> list;
    private List<String> leftData;

    private String[] left_item = new String[]{"产品", "设计", "管理", "运营", "职能", "市场", "资本", "技术", "其他"};

    private List<CommTags> selectList;
    private int lastPosition;//记录最后点击的位置

    private RightContentAdapter selectAdapter;

    private int mostSelect = 30;



    @Override
    protected int getResourceId() {
        return R.layout.activity_more_role;
    }

    @Override
    protected void init() {
        isSkill = getIntent().getBooleanExtra("skill",false);
        setHeadInfo();



        if(isSkill) {//技能才拥有左边分类
            initLeftMenu();
        }else {
            leftMune.setVisibility(View.GONE);
        }

        initSelectList();

        getHttpData();



        selectBtn.setOnClickListener(this);


        selectNum.setText(Html.fromHtml(getDesc()));
    }

    /**
     * 绑定选中数据
     */
    private void  initSelectList(){
        if(isSkill){//角色标签
            try {
                List<UserData.SkillsBean> skillses = (List<UserData.SkillsBean>) getIntent().getSerializableExtra("skilles");
                selectList =new ArrayList<>();
                for (UserData.SkillsBean skill: skillses) {
                    CommTags tag = new CommTags();
                    tag.setTagName(skill.getSkillName());
                    tag.setId(skill.getSkillId());
                    tag.setSelected(true);
                    selectList.add(tag);
                }
            }catch (Exception e){

            }
        }else{//行业标签
            try {
                List<UserData.IndustryBean> skillses = (List<UserData.IndustryBean>) getIntent().getSerializableExtra("industry");
                selectList =new ArrayList<>();
                for (UserData.IndustryBean skill: skillses) {
                    CommTags tag = new CommTags();
                    tag.setSelected(true);
                    tag.setTagName(skill.getIndustryName());
                    tag.setId(skill.getIndustryId());
                    selectList.add(tag);
                }
            }catch (Exception e){

            }
        }
    }
    /**
     * 初始化选中的标签
     */
    private void intSelectContent() {

        selectAdapter = new RightContentAdapter(mContext,selectList);
        LinearLayoutManager manger = new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false);
        selectContent.setLayoutManager(manger);
        selectAdapter.setOnItemListerner(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int position) {
                if(selectList!=null&&selectList.size()>position) {
                    CommTags tag = selectList.get(position);
                        selectList.remove(tag);

                    if(isSkill) {//针对技能
                        list.get(tag.getParentPosition()).getTags().get(tag.getPosition()).setSelected(false);
                        //刷新当前布局
                        addRightContent(list.get(lastPosition).getTags());
                    }else {//行业
                            list.get(tag.getPosition()).setSelected(false);
                        addRightContent(list);
                    }
                    selectAdapter.updataAdapter(selectList);
                    selectNum.setText(Html.fromHtml(getDesc()));
                }
            }
        });
        selectContent.setAdapter(selectAdapter);

    }

    /**
     * 请求接口数据
     */
    private void getHttpData() {
        JsonObject param = new JsonObject();
        if(isSkill) {//获取技能数据
            param.addProperty("type", 2);
            HttpHelper.getInstance(mContext).commonTagsList(param, GET_COMM_TAG_LIST_CODE, this);
        }else {//获取  行业数据
//            param.addProperty("type", 1);
            HttpHelper.getInstance(mContext).commonIndustryList(param, GET_COMM_INDUSTRY_LIST_CODE, this);
        }
    }

    /**
     * 设置头部信息
     */
    private void setHeadInfo() {
        leftIcon.setOnClickListener(this);
        leftIcon.setImageResource(R.mipmap.guanzhufanhui);
        leftIcon.setVisibility(View.VISIBLE);
        topName.setText("技能标签");
        topDesc.setVisibility(View.GONE);
        topName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        rightIcon.setVisibility(View.GONE);
    }

    /**
     * 初始化左边菜单
     */
    private void initLeftMenu() {
        leftAdapter = new LeftAdapter(mContext, null);
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        leftMune.setLayoutManager(manager);
        leftMune.setAdapter(leftAdapter);


        leftAdapter.setOnItemListener(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int position) {

                if(position!=lastPosition) {//防止重复点击
                    list.get(lastPosition).setSelected(false);
                    list.get(position).setSelected(true);

                    leftAdapter.updataAdapter(list);
                    addRightContent(list.get(position).getTags());
                    lastPosition = position;

                }
            }
        });
    }



    @Override
    public void onStart(int requestType) {
            loading.show();
    }

    @Override
    public void onCompleted(int requestType) {
        loading.cancel();
    }

    @Override
    public void onError(int requestType) {
        loading.cancel();
        ToasUtil.toast(mContext,"获取标签失败!");
    }

    @Override
    public void onNext(IModel data, int requestType) {
        if (data.getErrcode() == 0) {//请求成功

            if(requestType==GET_COMM_TAG_LIST_CODE){//技能标签
                list = data.getList(CommTags.class);
                if(list!=null&&list.size()>0) {
                    list.get(0).setSelected(true);
                    leftAdapter.updataAdapter(list);
                    addRightContent(list.get(0).getTags());
                }
            }else if(requestType==GET_COMM_INDUSTRY_LIST_CODE){
                list = data.getList(CommTags.class);
                addRightContent(list);
            }
            intSelectContent();
        }else {
            ToasUtil.toast(mContext,data.getMessage());
        }
    }

    /**
     * 添加右边内容
     * @param tags
     */
    private void addRightContent(List<CommTags> tags) {
        flowLayout.removeAllViews();
        if(tags == null)
            return;
        int size = tags.size();
        for (int i = 0; i < size; i++) {
            CommTags tag = tags.get(i);
            TextView text = (TextView) getLayoutInflater().inflate(R.layout.comm_tags_item,null);
            text.setText(tag.getTagName());
            flowLayout.addView(text);
            text.setTag(i);
            text.setOnClickListener(rightOnItemClick);

//

            boolean flag = isSelected(tag.getId(),i);//是否是被选中的  针对 第一次从前一个页面传过来的数据
            if(flag){
                tag.setSelected(true);

            }

            if(tag.isSelected()){
                text.setBackground(mContext.getResources().getDrawable(R.drawable.rbg_blue));
                text.setTextColor(mContext.getResources().getColor(R.color.theme_color));
            }else{
                text.setBackground(mContext.getResources().getDrawable(R.drawable.btn_rbg_gray));
                text.setTextColor(mContext.getResources().getColor(R.color.font_gray));
            }

        }
    }

    /**
     * 判断第一次 过来的选中状态
     * @param id
     * @return
     */
    private boolean isSelected(String id,int position) {
        if(selectList!=null){
            for (CommTags tag:selectList){
                if(id.equals(tag.getId())){
                    tag.setPosition(position);//记录当前选中的在数据中的位置
                    return true;
                }
            }
        }
      return false;
    }

    /**
     * 右边内容item点击
     */
    private View.OnClickListener   rightOnItemClick =new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            List<CommTags> commTagses =null;
            CommTags parentTag = null;
            if(isSkill){//技能标签
                 parentTag = list.get(lastPosition);
                 commTagses = parentTag.getTags();
            }else {
                commTagses =list;
            }
            CommTags commTags = commTagses.get(position);
            boolean contains =selectListContainsTag(commTags); //selectList.contains(commTags);
            if(!contains&&selectList.size()<mostSelect) {

                v.setBackground(mContext.getResources().getDrawable(R.drawable.rbg_blue));
                ((TextView)v).setTextColor(mContext.getResources().getColor(R.color.theme_color));
                commTags.setSelected(true);
                if(parentTag!=null) {
                    commTags.setParentId(parentTag.getId());
                    commTags.setParentPosition(lastPosition);
                }
                commTags.setPosition(commTagses.indexOf(commTags));
                selectList.add(commTags);
                selectAdapter.updataAdapter(selectList);
                selectContent.smoothScrollToPosition(selectList.size()-1);
                selectNum.setText(Html.fromHtml(getDesc()));
                if(selectList.size()==mostSelect-1){
//                    selectBtn.setEnabled(false);
                }
            }else if(contains){
                v.setBackground(mContext.getResources().getDrawable(R.drawable.btn_rbg_gray));
                ((TextView)v).setTextColor(mContext.getResources().getColor(R.color.font_gray));
                commTags.setSelected(false);
                selectList.remove(select_positio);
                selectAdapter.updataAdapter(selectList);
                selectNum.setText(Html.fromHtml(getDesc()));
            }
        }
    };

    /**
     * 判断选中列表中是否包含当前点击item
     * @param commTags
     * @return
     */

    /**临时记录 点击的Item在selectlist中的位置  针对第一次进来对象并不完全一样**/
    private int select_positio;
    private boolean selectListContainsTag(CommTags commTags) {
        select_positio =0;
        try {
            if(selectList!=null) {
                for (CommTags tag : selectList) {
                    if (commTags.getId().equals(tag.getId())) {
                        return true;
                    }
                    select_positio++;
                }
            }
        }catch (Exception e){

        }
        return  false;
    }


    private String getDesc(){
        StringBuilder sb = new StringBuilder();
        sb.append("你可以选择<font color='#1A98E5'>")
                .append(mostSelect)
                .append("</font>个，还可以选择<font color='#1A98E5'>")
                .append(mostSelect-selectList.size())
                .append("</font>个");
        return sb.toString();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case  R.id.icon_left:
//                handSelectTags();//处理选中的标签
                finish();
                break;
            case  R.id.select_btn:
                handSelectTags();//处理选中的标签
                break;
            default:
                break;
        }
    }


    private void handSelectTags() {
        List<CommTags> list = selectAdapter.getCommTags();
        if (isSkill) {//技能
            List<UserData.SkillsBean> roles = new ArrayList<>();
            for (CommTags tag:list) {
                UserData.SkillsBean role = new UserData.SkillsBean();
                role.setSkillId(tag.getId());
                role.setSkillName(tag.getTagName());
                roles.add(role);
            }
            Intent intent = new Intent();
            intent.putExtra("role", (Serializable) roles);
            setResult(INDUSTRY_RESULT_CODE,intent);
        } else {//行业
            List<UserData.IndustryBean> industrys = new ArrayList<>();
            for (CommTags tag:list) {
                UserData.IndustryBean role = new UserData.IndustryBean();
                role.setIsChecked(1);
                role.setIndustryId(tag.getId());
                role.setIndustryName(tag.getTagName());
                industrys.add(role);
            }
            Intent intent = new Intent();
            intent.putExtra("industry", (Serializable) industrys);
            setResult(INDUSTRY_RESULT_CODE,intent);
        }
        this.finish();
    }
}
